

<script lang="ts">
import { computed, defineComponent, ref, reactive, watch, watchEffect, onUnmounted } from "vue"
import { useI18n } from "vue-i18n";
import { getAssetsFile } from "@/utils/pub-use";
import { UserModule } from "@/store/modules/user";
import { getUserInfo, getOrderItemMax, getParameter, getOrderInfo, orderFee, invest, makeOrderItem } from "@/api";
import { showToast, showDialog, showConfirmDialog } from 'vant';
import { investList } from "@/utils/investList"
export default defineComponent({
    setup() {
        const { t } = useI18n();
        const open = ref(false)
        const pageLoading = ref(true)
        const loading = ref(false)
        const formData = reactive({
            insure: 0,
            orderNum: "",
            amount: ""
        })

        const time = computed(() => {
            let releaseTime = 1703142000;
            let timestamp = new Date().getTime() / 1000;
            let day = 86400;
            return (
                (releaseTime +
                    Math.ceil((timestamp - releaseTime) / day) * day -
                    timestamp) *
                1000
            );
        });
        const investCurrent = ref({})
        const userInfo = ref({})
        const checked = computed(() => {
            return (j) => {
                if (j < 10)
                    j = '0' + j;
                return j;
            }
        })
        const show = (item) => {
            open.value = true
            investCurrent.value = item
            formData.amount = investCurrent.value.minimal
            if (orderInfo.value['SR1'] != 0) {
                formData.orderNum = "1"
            } else if (orderInfo.value['SR2'] != 0) {
                formData.orderNum = "2"
            } else if (orderInfo.value['SR3'] != 0) {
                formData.orderNum = "3"
            }
        }
        const sendInvest = async () => {
            if (!Number(formData.amount)) return
            try {

                if (userInfo.value.USDT < Number(formData.amount)) {
                    showToast(t("layout.theBalanceUSDTIsOnly") + userInfo.value.USDT);
                    return;
                }
                if (Number(investCurrent.value.minimal) > Number(formData.amount)) {
                    showToast(t("layout.minimumQuantity") + investCurrent.value.minimal);
                    return;
                }
                if (Number(formData.amount) > (parameter.value['Invest' + investCurrent.value.day] - userInfo.value['TotalInvest' + (investCurrent.value.index + 1)])) {
                    showToast(`${t('layout.' + investList[investCurrent.value.index].name)}${t('layout.TheMaximumAmountIs')}${parameter.value['Invest' + investCurrent.value.day]}`);
                    return
                }
                loading.value = true
                await UserModule.verifyToken();
                const res = await invest({ investDay: investCurrent.value.day, ...formData })
                if (res.data.code == 20) {
                    open.value = false
                    showDialog({ title: `${t("layout.success")}` })
                } else {
                    showToast(res.data.message)
                }
                loadData()
            } catch (error) {
                showToast(error)
            }
            loading.value = false
        }
        const sendMakeOrderItem = async () => {
            if (!Number(formData.amount)) return
            if (userInfo.value.USDT < Number(formData.amount)) {
                showToast(t("layout.theBalanceUSDTIsOnly") + userInfo.value.USDT);
                return;
            }
            if (Number(investCurrent.value.minimal) > Number(formData.amount)) {
                showToast(t("layout.minimumQuantity") + investCurrent.value.minimal);
                return;
            }

            // if (Number(formData.amount) > orderItemMax.value) {
            //     showToast(t('layout.CurrentQuota') + orderItemMax.value);
            //     return
            // }
            // if (Number(formData.amount) > Math.min(orderItemMax.value, orderInfo.value.R - orderInfo.value.C)) {
            //     showToast(t('layout.CurrentQuota') + Math.min(orderItemMax.value, orderInfo.value.R - orderInfo.value.C))
            //     return
            // }
            if (Number(formData.amount) > orderItemMax.value) {
                showToast(t('layout.CurrentQuota') + orderItemMax.value)
                return
            }

            if (Number(userInfo.value.Order50)) {
                try {
                    loading.value = true
                    await UserModule.verifyToken();
                    let res = await makeOrderItem({ investDay: investCurrent.value.day, ...formData })
                    if (res.data.code == 20) {
                        open.value = false
                        showDialog({ title: `${t("layout.success")}` })
                    } else {
                        showToast(res.data.message)
                    }
                    loadData()
                } catch (error) {
                    showToast(error)
                }
                loading.value = false
            } else {
                showConfirmDialog({
                    title: t('layout.Arequired'),
                    beforeClose: async function (action: string): Promise<boolean> {
                        if (action === "confirm") {
                            try {
                                await UserModule.verifyToken();
                                await orderFee()
                                let res = await makeOrderItem({ investDay: investCurrent.value.day, ...formData })
                                if (res.data.code == 20) {
                                    open.value = false
                                    showDialog({ title: `${t("layout.success")}` })
                                } else {
                                    showToast(res.data.message)
                                }
                                loadData()
                            } catch (error) {
                                showToast(error)
                            }
                            return false;
                        } else {
                            return true;
                        }
                    },
                })
                    .then(async () => {
                        loading.value = false
                    })
                    .catch(() => {
                        loading.value = false
                    });
            }

        }
        const orderInfo = ref({})
        const orderItemMax = ref(0)
        const parameter = ref({})
        const loadData = async () => {
            pageLoading.value = true
            userInfo.value = (await getUserInfo()).data.data.UserInfo || {}
            await getParameter().then(res => {
                parameter.value = res.data.data.Parameter
            })
            getOrderInfo().then(res => {
                orderInfo.value = res.data.data.DayOrderInfo || {}
                // orderInfo.value.Status = 0
                // orderInfo.value.C = 20
            })
            getOrderItemMax().then(res => {
                orderItemMax.value = Number(res.data.data?.OrderItemMax || 0)
            })
            pageLoading.value = false
        }
        const timer = ref();
        watchEffect(() => {
            timer.value = setInterval(async () => {
                userInfo.value = (await getUserInfo()).data.data.UserInfo || {}
            }, 1500);
        });
        onUnmounted(() => {
            clearInterval(timer.value);
        });
        watch(
            () => UserModule.userAddr,
            (newUserAddr: string) => {
                if (newUserAddr) {
                    loadData();
                }
            },
            { immediate: true }
        );
        return {
            open,
            loading,
            formData,
            investList,
            time,
            checked,
            userInfo,
            pageLoading,
            investCurrent,
            orderItemMax,
            orderInfo,
            parameter,
            getAssetsFile,
            sendInvest,
            show,
            sendMakeOrderItem
        }
    }
})
</script>
<template>
    <div class="page">
        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
            <van-swipe-item><img src="@/assets/image/banner.png" alt="" srcset=""></van-swipe-item>
        </van-swipe>
        <div class="investList-block" v-for="(item, index) in investList">
            <div class="name">
                <div class="name_cell"><i></i>{{ $t(`layout.${item.name}`) }} </div><img src="@/assets/image/image2.png"
                    alt="" srcset="">
            </div>
            <div class="investList">
                <div class="left" v-if="index != 3">
                    <div class="label">{{ $t('layout.cycleDay') }} <span>{{ item.day }}</span></div>
                    <div class="label">{{ $t('layout.minimumQuantity') }} <span>{{ item.minimal }}</span></div>
                </div>
                <div class="overtime" v-else>
                    <div class="label">{{ $t('layout.StartingTime') }}</div>
                    <van-count-down :time="time">
                        <template #default="timeData">
                            <span class="block">{{ checked(timeData.days) }}</span>
                            <span class="colon">{{ $t('layout.sky') }}</span>
                            <span class="block">{{ checked(timeData.hours) }}</span>
                            <span class="colon">{{ $t('layout.hour') }}</span>
                            <span class="block">{{ checked(timeData.minutes) }}</span>
                            <span class="colon">{{ $t('layout.point') }}</span>
                            <span class="block">{{ checked(timeData.seconds) }}</span>
                            <span class="colon">{{ $t('layout.Second') }}</span>
                        </template>
                    </van-count-down>
                    <van-progress :percentage="(orderInfo.Status != 2 ? Number((orderInfo.C || 0).toFixed(0)) : 0) || 0"
                        color="rgba(11, 166, 98, 1)" />
                </div>
                <van-image fit="contain" :src="item.image" />
            </div>
            <van-button type="primary" @click="show(item)">{{ $t('layout.ParticipateNow') }}</van-button>
        </div>
    </div>
    <!-- 自定义图标 -->
    <van-popup v-model:show="open" closeable position="bottom" round>
        <div class="popup">
            <div class="title"><img src="@/assets/image/image4.png" alt="" srcset=""> {{ $t(`layout.${investCurrent.name}`)
            }}</div>
            <van-tabs v-model:active="formData.insure" :class="{ hi: investCurrent.index != 3 }">
                <div v-if="investCurrent.index == 3">
                    <van-tab :title="$t('layout.insurancearea')"></van-tab>
                    <van-tab :title="$t('layout.nonInsuranceArea')"></van-tab>
                    <van-radio-group v-model="formData.orderNum">
                        <van-radio :name="(index + 1) + ''" v-for="(item, index) in  ['one', 'two', 'three'] "
                            :disabled="orderInfo['SR' + (index + 1)] == 0" :key="index">
                            <template #icon="props">
                                <van-button type="primary" class="radio_button"
                                    :disabled="orderInfo['SR' + (index + 1)] == 0" :class="{ active: props.checked }">{{
                                        $t(`layout.${item}`)
                                    }}</van-button>
                            </template>
                        </van-radio>
                    </van-radio-group>
                </div>
                <div class="amount-box">
                    <div class="Details" v-if="investCurrent.index == 3 && orderInfo.Status != 2">
                        <ul v-if="orderInfo['Details' +
                            formData.orderNum]" style="padding:0.3rem;display: block;">
                            <li v-for="(item, index) in orderInfo['Details' +
                                formData.orderNum].split('；')" :key="index">
                                {{ item }}
                            </li>
                        </ul>
                    </div>
                    <div class="name">{{ $t('layout.investmentAmount') }}
                        <!-- <span v-if="investCurrent.index == 3">{{
                            $t('layout.CurrentQuota') }}：
                            {{ Math.min(orderItemMax, orderInfo.R - orderInfo.C) }}
                        </span>
                        <span v-else>
                            {{ $t('layout.CurrentQuota') }}：
                            {{ parameter['Invest' +
                                investCurrent.day] - userInfo['TotalInvest' + (investCurrent.index + 1)] }}
                        </span> -->
                        <span v-if="investCurrent.index == 3"> {{ $t('layout.CurrentQuota') }}：{{ orderItemMax }}</span>
                        <span v-else>
                            {{ $t('layout.CurrentQuota') }}：{{ (parameter['Invest' +
                                investCurrent.day] - userInfo['TotalInvest' + (investCurrent.index + 1)])
                                < 0 ? 0 : (parameter['Invest' + investCurrent.day] - userInfo['TotalInvest' +
                                    (investCurrent.index + 1)]) }} </span>
                    </div>
                    <van-field v-model="formData.amount" :placeholder="$t('layout.PleaseEnterQuantity')">
                        <template #right-icon>
                            <span>{{ userInfo.USDT || 0 }} USDT</span>
                            <!-- <span class="all" @click="formData.amount = userInfo.USDT">{{ $t("layout.all") }}</span> -->
                        </template>
                    </van-field>
                    <div class="text" v-if="investCurrent.index == 3">{{
                        $t('layout.expectedToGain')
                    }}：
                        <template v-if="formData.orderNum && orderInfo.Status != 2">
                            <template v-if="!formData.insure">
                                {{ (formData.amount * (0.57 * (orderInfo['SR' + formData.orderNum]) + 0.38)).toFixed(0) }}
                            </template>
                            <template v-else>{{
                                (formData.amount *
                                    (orderInfo['SR' + formData.orderNum])).toFixed(0) }}</template>
                        </template>
                        <template v-else>0</template>
                    </div>
                </div>
                <van-button type="primary" class="sendInvest" v-if="investCurrent.index == 3" @click="sendMakeOrderItem"
                    :disabled="orderInfo.Status == 1 || orderInfo.Status == 2 || orderInfo['SR' + (formData.orderNum || 1)] == 0"
                    :loading="loading">{{
                        $t('layout.ParticipateNow') }}</van-button>
                <van-button type="primary" v-else class="sendInvest" @click="sendInvest" :loading="loading">{{
                    $t('layout.ParticipateNow') }}</van-button>
            </van-tabs>
        </div>
    </van-popup>
</template>

<style lang="less" scoped>
.page {
    padding: 0 15px 15px 15px;

    .my-swipe {
        margin-bottom: 15px;

        .van-swipe-item {
            color: #fff;
            font-size: 20px;
            text-align: center;

            img {
                height: 111px;
            }
        }
    }

    .investList-block {
        margin-bottom: 7px;
        padding-bottom: 20px;
        background: url("@/assets/image/image1.png") center/cover no-repeat;

        .investList {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .left {
                .label {
                    margin: 0 0 8px 17px;
                    width: 154px;
                    height: 33px;
                    padding: 0 16px;
                    line-height: 33px;
                    background: #FAFAFA;
                    border-radius: 6px;
                    box-sizing: border-box;

                    span {
                        margin-left: 8px;
                        font-size: 16px;
                        font-weight: bold;
                        color: #0BA662;
                        letter-spacing: 1px;
                    }
                }
            }

            .overtime {
                margin-left: 16px;
                width: 154px;
                height: 74px;
                padding: 8px 10px;
                text-align: center;
                background: #FAFAFA;
                border-radius: 6px;
                box-sizing: border-box;

                .label {
                    font-size: 12px;
                    font-weight: 400;
                    color: #1F2120;
                }

                .van-count-down {
                    margin-top: 9px;

                    .block {
                        margin: 0 1px;
                        font-size: 14px;
                        font-weight: bold;
                        color: #0BA662;
                    }

                    .colon {
                        font-size: 14px;
                        font-weight: 400;
                        color: #1F2120;
                    }
                }

                .van-progress {
                    margin-top: 10px;
                }
            }

            .van-image {
                width: 160px;
                height: 135px;
            }
        }

        .name {
            width: 166px;
            height: 33px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 15px;
            font-weight: 500;
            color: #0BA662;
            background: rgba(255, 255, 255, 0.6);
            border-radius: 6px 0px 50px 0px;
            border: 1px solid #FFFFFF;

            .name_cell {
                display: flex;
                align-items: center;
            }

            i {
                margin: 0 10px;
                width: 6px;
                height: 6px;
                border-radius: 50%;
                border: 2px solid rgba(11, 166, 98, 1);
                box-sizing: border-box;
            }

            img {
                margin-right: 20px;
                width: 22px;
                height: 16px;
            }
        }

        .van-button {
            display: flex;
            justify-content: center;
            width: 313px;
            margin: 0 auto;
        }
    }
}

.popup {
    background: #0BA662;

    .title {
        position: relative;
        height: 55px;
        display: flex;
        align-items: center;
        justify-content: center;
        line-height: 55px;
        font-size: 18px;
        font-weight: 500;
        color: #FFFFFF;

        img {
            position: absolute;
            left: 20px;
            width: 22px;
            height: 16px;
        }
    }

    .van-tabs {
        padding: 20px 15px;
        background: #fff;
        border-radius: 10px 10px 0 0;
        overflow: hidden;

        &.hi {
            &:deep(.van-tabs__wrap) {
                height: 0;
            }
        }

        &:deep(.van-tabs__wrap) {


            .van-tabs__nav {
                width: 344px;
                height: 45px;
                background: rgba(11, 166, 98, 0.1);
                border-radius: 8px;
                border: 1px solid #FFFFFF;

                .van-tab {
                    &.van-tab--active {
                        width: 172px;
                        height: 44px;
                        background: #0BA662;
                        border-radius: 8px;
                        color: #fff;
                    }
                }

                .van-tabs__line {
                    display: none;
                }
            }
        }

        .van-radio-group {
            margin-top: 17px;
            display: flex;
            justify-content: space-between;

            .van-radio {


                &:deep(.van-radio__icon) {
                    width: 110px;
                    height: 45px;
                    background: rgba(11, 166, 98, 0.1);
                    border-radius: 6px;

                    &.van-radio__icon--checked {
                        border: 1px solid #0BA662;
                        overflow: hidden;
                        box-sizing: border-box;
                        background: #0BA662;

                        .van-button__content {
                            .van-button__text {
                                font-size: 15px;
                                font-weight: 600;
                                color: #fff;
                            }
                        }
                    }

                    .van-button__content {
                        .van-button__text {
                            font-size: 18px;
                            font-weight: bold;
                            color: #0BA662;
                        }
                    }
                }
            }
        }

        .amount-box {
            margin-top: 10px;

            .Details {
                line-height: 30px;
                font-size: 14px;
                background: rgba(11, 166, 98, 0.1);
                border-radius: 6px;

                ul {
                    li {}
                }
            }

            .name {
                margin-top: 10px;
                display: flex;
                justify-content: space-between;

                span {
                    color: #0BA662;
                }
            }

            .van-field {
                margin-top: 12px;
                height: 45px;
                background: rgba(11, 166, 98, 0.06);
                border-radius: 6px;
                color: #0BA662;
                border: 1px solid #0BA662;

                &:deep(input) {
                    color: #0BA662;
                }
            }

            .text {
                margin-top: 8px;
            }
        }

        .sendInvest {
            margin-top: 20px;
        }



        .radio_button {
            width: 110px;
            height: 45px;
            background: rgba(11, 166, 98, .1);
            border-radius: 6px;

            &.van-button--disabled {
                opacity: 0.2;
            }
        }
    }

    .all {
        display: inline-block;
        margin-left: 10px;
        padding-left: 10px;
        border-left: 1px dashed var(--van-field-right-icon-color);
    }
}
</style>
